<template>
  <div class="MyInfo">
    <MyHeader>
      <span>我的信息</span>
    </MyHeader>
    <div class="MyInfoContent">
      <!-- 个信息展示 -->
      <el-descriptions
        class="margin-top"
        title="个人信息"
        :column="1"
        border
        vertical
      >
        <template slot="extra">
          <el-button
            type="success"
            @click="modifyPortrait"
            size="small"
            style="margin-left: 20px"
            >更换头像</el-button
          >
          <el-button
            type="success"
            @click="modifyPayPwd"
            size="small"
            style="margin-left: 20px"
            >修改支付密码</el-button
          >
          <el-button type="success" @click="modifyPersonInfo" size="small"
            >修改个人信息</el-button
          >
        </template>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            用户名
          </template>
          {{ userInfo.username }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <img
              src="../../assets/img/password.png"
              style="width: 15px; height: 15px"
              alt=""
            />
            登录密码
          </template>
          {{ userInfo.password }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <img
              src="../../assets/img/email.png"
              style="width: 15px; height: 15px"
              alt=""
            />
            邮箱
          </template>
          {{ userInfo.email }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            手机号
          </template>
          {{ userInfo.phone }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <img
              src="../../assets/img/gender.png"
              style="width: 15px; height: 15px"
              alt=""
            />
            性别
          </template>
          {{ userInfo.gender }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-custom"></i>
            客户类型
          </template>
          {{ userInfo.type }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-location-outline"></i>
            地址
          </template>
          {{ userInfo.address }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <img
              src="../../assets/img/money.png"
              style="width: 15px; height: 15px"
              alt=""
            />
            余额
          </template>
          <el-tag size="small">{{ userInfo.money }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <!-- 修改个人头像 -->
      <!-- <MyPortrait :visiblePortrait="visiblePortrait"></MyPortrait> -->
      <el-dialog
        title="修改个人头像"
        :visible.sync="dialogVisiblePortrait"
        width="30%"
        :before-close="handleClose"
      >
        <el-upload
          class="avatar-uploader"
          action="http://localhost:3000/user/getPortrait"
          :data="{ userId }"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-remove="handleAvatarRemove"
          :auto-upload="false"
          :on-change="imgPreview"
          :before-remove="beforeRemove"
          :limit="1"
          ref="upload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleAvatarRemove">取 消</el-button>
          <el-button type="primary" @click="confirmModifyPortrait"
            >保存</el-button
          >
        </span>
      </el-dialog>
      <!-- 修改用户支付密码弹出层 -->
      <el-dialog
        title="修改支付密码"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-input
          placeholder="旧支付密码"
          v-model="oldPayPwd"
          clearable
          style="margin-bottom: 10px; margin-left: 5px"
          type="password"
        >
        </el-input>
        <el-input
          placeholder="新支付密码（3-10位）"
          v-model="newPayPwd"
          clearable
          style="margin-bottom: 15px; margin-left: 5px"
          type="password"
        >
        </el-input>
        <el-input
          placeholder="再次输入新支付密码（3-10位）"
          v-model="newPayPwdAgain"
          clearable
          style="margin-bottom: 10px; margin-left: 5px"
          type="password"
        >
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmModify">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户个人信息弹出层 -->
      <el-dialog
        title="修改个人信息"
        :visible.sync="dialogVisible1"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          status-icon
          :rules="rules"
          :model="modifyForm"
          ref="modifyForm"
          style="color: black"
        >
          <el-form-item
            label="用户名"
            name="modify"
            label-width="70px"
            prop="username"
          >
            <el-input
              type="text"
              v-model="modifyForm.username"
              :placeholder="userInfo.username"
              disabled
            />
          </el-form-item>
          <el-form-item
            label="密码"
            name="modify"
            label-width="70px"
            prop="password"
          >
            <el-input type="password" v-model="modifyForm.password" />
          </el-form-item>
          <el-form-item
            label="确认密码"
            name="modify"
            label-width="70px"
            prop="confirmPassword"
          >
            <el-input type="password" v-model="modifyForm.confirmPassword" />
          </el-form-item>
          <el-form-item label="性别" name="modify" label-width="70px" prop="">
            <el-radio v-model="modifyForm.gender" :label="0">男</el-radio>
            <el-radio v-model="modifyForm.gender" :label="1">女</el-radio>
          </el-form-item>
          <el-form-item
            label="邮箱"
            name="modify"
            label-width="70px"
            prop="email"
          >
            <el-input type="text" v-model="modifyForm.email" />
          </el-form-item>
          <el-form-item
            label="手机号码"
            name="modify"
            label-width="70px"
            prop="phone"
          >
            <el-input type="text" v-model="modifyForm.phone" />
          </el-form-item>
          <el-form-item label="地址" name="modify" label-width="70px" prop="">
            <el-select
              v-model="province"
              placeholder="请选择省份"
              @change="changeProvince"
              style="width: 155px"
            >
              <el-option
                v-for="(item, index) in address1"
                :key="index"
                :label="item.title"
                :value="item.title"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="city"
              placeholder="请选择市"
              @change="changeCity"
              style="width: 155px"
            >
              <el-option
                v-for="(item, index) in address2"
                :key="index"
                :label="item.title"
                :value="item.title"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="county"
              placeholder="请选择县或区"
              style="width: 155px"
            >
              <el-option
                v-for="(item, index) in address3"
                :key="index"
                :label="item.title"
                :value="item.title"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label=""
            name="modify"
            label-width="70px"
            prop="specificArea"
          >
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入具体地址..."
              v-model="modifyForm.specificArea"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="infoCancel">取 消</el-button>
          <el-button type="primary" @click="submitForm('modifyForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import MyHeader from "../../components/MyHeader.vue";
// import MyPortrait from "../../components/MyCenter/MyPortrait.vue";

export default {
  name: "MyInfo",
  data() {
    return {
      userId: "",
      userInfo: {},
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisiblePortrait: false,
      imageUrl: "",

      oldPayPwd: "",
      newPayPwd: "",
      newPayPwdAgain: "",
      //修改个人信息表单数据
      modifyForm: {
        username: "",
        password: "",
        confirmPassword: "",
        gender: 0,
        email: "",
        phone: "",
        address: "",
        specificArea: "",
      },
      address1: require("../../assets/js/area"),
      province: "",
      address2: "",
      city: "",
      address3: "",
      county: "",

      //验证规则匹配
      rules: {
        //验证密码
        password: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请输入密码！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        //验证确认密码
        confirmPassword: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请再次输入密码"));
              } else if (value !== this.modifyForm.password) {
                callback(new Error("两次输入密码不一致!"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        //验证注册邮箱
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        //验证手机号
        phone: [
          {
            validator: (rule, value, callback) => {
              var phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
              if (phoneReg.test(value)) {
                callback();
              } else {
                callback(new Error("手机格式错误"));
              }
            },
            trigger: "blur",
          },
        ],
        specificArea: [
          {
            validator: (rule, value, callback) => {
              if (value == "") {
                callback(new Error("填好地址啊！！"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  components: {
    MyHeader,
    // MyPortrait,
  },
  methods: {
    //修改支付密码
    modifyPayPwd() {
      this.dialogVisible = true;
    },
    //修改个人信息
    modifyPersonInfo() {
      this.dialogVisible1 = true;
    },
    //更换头像
    modifyPortrait() {
      this.dialogVisiblePortrait = true;
    },

    //提交按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.modifyForm.address.trim() !== "") {
          // console.log(this.modifyForm)
          const { password, gender, email, phone, address } = this.modifyForm;
          //修改信息请求
          const p = new Promise((resolve, reject) => {
            axios
              .post("http://localhost:3000/user/modifyPersonInfo", {
                password,
                gender,
                email,
                phone,
                address,
                userId: this.userId,
              })
              .then(
                (response) => {
                  resolve(response);
                },
                (error) => {
                  reject(error);
                }
              );
          });
          p.then(
            (response) => {
              // console.log(response)
              if (response.data.isExist) {
                alert(response.data.msg);
                this.dialogVisible1 = false;
              } else {
                alert("修改成功！！");
                this.dialogVisible1 = false;
                const p2 = new Promise((resolve, reject) => {
                  axios
                    .get(
                      `http://localhost:3000/user/selectUserInfo?userId=${this.userId}`
                    )
                    .then(
                      (response) => resolve(response),
                      (error) => reject(error)
                    );
                });
                p2.then(
                  (response) => {
                    // console.log(response)
                    this.userInfo = response.data[0];
                  },
                  (error) => {
                    console.log(error);
                  }
                );
              }
            },
            (error) => {
              console.log(error);
            }
          );
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    //切换省份
    changeProvince() {
      this.city = "";
      this.county = "";
      // console.log("6666666")
      this.address2 = this.address1.filter((item) => {
        return this.province === item.title;
      });
      // console.log(this.address2[0].children)
      this.address2 = this.address2[0].children;
    },
    //切换市
    changeCity() {
      this.county = "";
      this.address3 = this.address2.filter((item) => {
        return this.city == item.title;
      });
      this.address3 = this.address3[0].children;
    },
    //关闭弹出层
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.modifyForm.password = "";
          this.modifyForm.confirmPassword = "";
          this.modifyForm.email = "";
          this.modifyForm.phone = "";
          this.modifyForm.address = "";
          this.modifyForm.specificArea = "";
          done();
        })
        .catch(() => {});
    },

    //个人信息取消
    infoCancel() {
      this.dialogVisible1 = false;
      /* let { password, confirmPassword, email, phone, address, specificArea } =
        this.modifyForm; */
      this.modifyForm.password = "";
      this.modifyForm.confirmPassword = "";
      this.modifyForm.email = "";
      this.modifyForm.phone = "";
      this.modifyForm.address = "";
      this.modifyForm.specificArea = "";
    },

    //确定修改支付密码
    confirmModify() {
      var isRight = false;
      //从数据库获取用户密码
      const p = new Promise((resolve, reject) => {
        axios
          .get(
            `http://localhost:3000/user/getUserPaypwd?userId=${this.userId}&paypwd=${this.oldPayPwd}`
          )
          .then(
            (response) => {
              resolve(response);
            },
            (error) => {
              reject(error);
            }
          );
      });
      p.then(
        (response) => {
          console.log(response);
          isRight = response.data.pwdIsRight;
          if (
            this.oldPayPwd.trim() === "" ||
            this.newPayPwd.trim() === "" ||
            this.newPayPwdAgain.trim() === ""
          ) {
            alert("输入不能为空！！");
          } else if (!isRight) {
            alert("旧密码输入错误！！！");
            this.oldPayPwd = "";
            this.newPayPwd = "";
            this.newPayPwdAgain = "";
          } else if (this.newPayPwdAgain !== this.newPayPwd) {
            alert("两次输入的新密码不正确！！");
            this.newPayPwd = "";
            this.newPayPwdAgain = "";
          } else if (this.newPayPwd.length < 3) {
            alert("新密码太短了");
            this.newPayPwd = "";
            this.newPayPwdAgain = "";
          } else if (this.newPayPwd.length > 10) {
            alert("新密码太长啦");
            this.newPayPwd = "";
            this.newPayPwdAgain = "";
          } else {
            //重置密码
            const p1 = new Promise((resolve, reject) => {
              axios
                .post("http://localhost:3000/user/modifyUserPayPwd", {
                  userId: this.userId,
                  newPayPwd: this.newPayPwd,
                })
                .then(
                  (response) => resolve(response),
                  (error) => reject(error)
                );
            });
            p1.then(
              (response) => {
                alert(response.data.msg);
                this.dialogVisible = false;
              },
              (error) => {
                console.log(error);
              }
            );
          }
        },
        (error) => {
          console.log(error);
        }
      );
      // console.log("isfdfd",isRight)
    },

    //确认修改头像
    confirmModifyPortrait() {
      this.$refs.upload.submit();
      this.dialogVisiblePortrait = false;
    },
    //图片上传成功的回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log("res", res, file);
    },
    //图片上传之前的回调
    beforeAvatarUpload(file) {
      // console.log("111", file);
      const isJPG = file.type === "image/jpeg";
      const isGIF = file.type === "image/gif";
      const isPNG = file.type === "image/png";
      const isBMP = file.type === "image/bmp";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.common.errorTip("上传图片必须是JPG/GIF/PNG/BMP 格式!");
      }
      if (!isLt2M) {
        this.common.errorTip("上传图片大小不能超过 2MB!");
      }
      return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
    },
    //图片移除的回调
    handleAvatarRemove(file, fileList) {
      console.log(file, fileList);
      this.dialogVisiblePortrait = false;
    },
    //图片移出之前的回调
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //获取选取了哪张照片
    imgPreview(file) {
      let fileName = file.name;
      // console.log("fileName:", fileName, fileList);
      let regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
      if (regex.test(fileName.toLowerCase())) {
        // console.log("this.imageUrl = URL.createObjectURL(file.raw);");
        // this.imageUrl = file.url;
        this.imageUrl = URL.createObjectURL(file.raw);
      } else {
        this.$message.error("请选择图片文件");
      }
    },
  },
  mounted() {
    this.userId = this.$cookie.get("userId");
    const p = new Promise((resolve, reject) => {
      axios
        .get(`http://localhost:3000/user/selectUserInfo?userId=${this.userId}`)
        .then(
          (response) => resolve(response),
          (error) => reject(error)
        );
    });
    p.then(
      (response) => {
        // console.log(response)
        this.userInfo = response.data[0];
      },
      (error) => {
        console.log(error);
      }
    );
  },
  updated() {
    //整合地址
    this.modifyForm.address =
      this.county === "" && this.modifyForm.specificArea !== ""
        ? ""
        : this.province +
          "省" +
          this.city +
          "市" +
          this.county +
          this.modifyForm.specificArea;
  },
};
</script>

<style scoped lang='less'>
.MyInfo {
  width: 100%;
  min-height: 600px;
  background-color: white;
  .MyInfoContent {
    margin: 20px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>